//
//  WbUserAccountViewModel.swift
//  Weibo
//
//  Created by HH on 16/12/3.
//  Copyright © 2016年 Weibo. All rights reserved.
//

import UIKit
import YYModel

class WbUserAccountViewModel: NSObject {
    
    static let sharedUserAccount:WbUserAccountViewModel = WbUserAccountViewModel()
    
    var accessToken:String? {
        
        guard let token = userInfo?.access_token else {
            return nil
        }
        
        if userInfo?.expiresDate?.compare(Date()) == ComparisonResult.orderedDescending{
            return token
        }else{
            return nil
        }
        
    }
    
    //判断是否登录
    var isLogin:Bool{
        
        //根据有无accessToken来判断
        return accessToken != nil
    }
    
    //
    var userInfo:WbUserInfoModel?{
        return WbUserInfoModel.loadUserInfo()
    }
    
   
    
    
    
    //获取Access_token
    func loadRequestAccess_token(code:String,complete:@escaping (Bool)->()){
        
        WbNetworking.sharedTools.requestAccess_token(code: code, complete: {(response, error) -> () in
            
            if error != nil{
                print(error!)
                
                complete(false)
                
                return
            }else{
                
                print(response!)
            
                
                let userInfoModel = WbUserInfoModel.yy_model(withJSON: response!)
                
                
                
                self.loadRequesdUserInfo(userInfo: userInfoModel!, complete: complete)
                
                /*
                 {
                 "access_token" = "2.00eQO8yFm9v8aB8ad188c9f6SND8AB";
                 "expires_in" = 157679999;
                 "remind_in" = 157679999;
                 uid = 5473734024;
                 }
                 
                 */
                
            }
            
        })
        
    }
    
    //获取UserInfo
    private func loadRequesdUserInfo(userInfo:WbUserInfoModel,complete:@escaping (Bool)->()){
        
        WbNetworking.sharedTools.requestUserInfo(userInfo: userInfo, complete: {(response, error) -> () in
            
            if error != nil{
                print(error!)
                print("获取信息失败")
                
                complete(false)
                return
            }
            
            print("获取信息成功")
            
            let dict = response as! [String:Any]
//            let userInfoModel = WbUserInfoModel.yy_model(withJSON: response!)
            
            userInfo.name = dict["name"] as! String?
            userInfo.avatar_large = dict["avatar_large"] as! String?
            
            userInfo.saveUserInfo()
            complete(true)
        
        })
    }

}
